package com.flexcloudsdk.capabilities;
import java.util.HashSet;

import java.util.logging.Logger;

import com.google.appengine.api.capabilities.CapabilitiesService;
import com.google.appengine.api.capabilities.CapabilitiesServiceFactory;
import com.google.appengine.api.capabilities.Capability;
import com.google.appengine.api.capabilities.CapabilityState;
import com.google.appengine.api.capabilities.CapabilityStatus;

public class CloudCapabilities {
	private static final Logger log = Logger.getLogger(CloudCapabilities.class.getName());
	private String sourceClass;
	private String sourceMethod;
	private Capability capabilities;
	private CapabilitiesService IService;
	private CapabilityState state;
	private CapabilityStatus status;
	private HashSet<String> serviceList = new HashSet<String>();
	
	public CloudCapabilities() {
		log.info("CloudCapabilities has been created by BlazeDS");
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		sourceClass = CloudCapabilities.class.getName();
	
		IService = CapabilitiesServiceFactory.getCapabilitiesService();
		serviceList.add(Capability.BLOBSTORE.getName());
		serviceList.add(Capability.DATASTORE.getName());
		serviceList.add(Capability.DATASTORE_WRITE.getName());
		serviceList.add(Capability.IMAGES.getName());
		serviceList.add(Capability.MAIL.getName());
		serviceList.add(Capability.MEMCACHE.getName());
		serviceList.add(Capability.TASKQUEUE.getName());
		serviceList.add(Capability.URL_FETCH.getName());
		serviceList.add(Capability.XMPP.getName());
	}
	
	public  String getServiceState(String service) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);
		String currentStatus = "";
		capabilities = new Capability(service);
		state = IService.getStatus(capabilities);
		status = state.getStatus();
		if (status.compareTo(CapabilityStatus.ENABLED) == 0)
			currentStatus = "enabled";
		else if (status.compareTo(CapabilityStatus.DISABLED) == 0)
			currentStatus = "disabled";
		else if (status.compareTo(CapabilityStatus.SCHEDULED_MAINTENANCE) == 0)
			currentStatus = "maintenance";
		else if (status.compareTo(CapabilityStatus.UNKNOWN) == 0)
			currentStatus = "unknown";
		return currentStatus;
	}
	
	public boolean isServiceUp(String service) {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		String status = getServiceState(service);
		boolean flag = false;
		if (status.equals("enabled"))
			flag = true;
		return flag;
	}
	
	public HashSet<String> getServices() {
		sourceMethod = Thread.currentThread().getStackTrace()[1].getMethodName().toString();
		log.info("Executing: " + sourceClass + "." + sourceMethod);

		return serviceList;
	}
	
	
}
